<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <form action="/"
          class="fix-top">
      <!-- 搜索 -->
      <van-search background="#3296fa"
                  show-action
                  v-model="searchValue"
                  @search="onSearch"
                  @cancel="$router.back()"
                  @clear="isResultShow=false"
                  placeholder="请输入搜索关键词" />
    </form>
    <!-- 内容区域 -->

    <!-- 搜索结果 -->
    <!-- <search-result  v-if="isResultShow"></search-result> -->
    <!-- 搜索建议 -->
    <!-- <search-suggestion :search-value="searchValue" @search="onSearch"   v-else-if="searchValue"></search-suggestion> -->
    <!-- 搜索历史 -->
    <!-- <search-history  v-else></search-history> -->

    <!-- 搜索结果 -->
    <search-result :search-value="searchValue"
                   v-if="isResultShow && searchValue"></search-result>
    <!-- 搜索建议 -->
    <search-suggestion :search-value="searchValue"
                       @search="onSearch"
                       v-if="searchValue && !isResultShow"></search-suggestion>
    <!-- 搜索历史 -->
    <search-history @search="onSearch"
                    :history-list="searchHistoryList"
                    v-if="!searchValue && !isResultShow"></search-history>

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import searchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storage'
export default {
  components: { searchSuggestion, SearchResult, SearchHistory },
  name: 'Search',
  data () {
    return {
      searchValue: '', // 搜索框绑定的数据
      isResultShow: false, // 是否显示搜索结果
      searchHistoryList: getItem('TOUTIAO-SEARCH') || [] // 搜索历史记录
    }
  },
  methods: {
    // 搜索框的输入确定事件
    onSearch (value) {
      console.log(value)
      // value 就是输入框的数据
      this.searchValue = value
      this.isResultShow = true
      // 保存搜索历史
      const idx = this.searchHistoryList.findIndex(item => item === value)
      if (idx !== -1) this.searchHistoryList.splice(idx, 1)
      this.searchHistoryList.unshift(value)
      // 保存本地
      setItem('TOUTIAO-SEARCH', this.searchHistoryList)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container{
  /deep/.van-search__action{
    color: #fff;
  }
  .fix-top{
    // 粘性布局
    position: sticky;
    top: 0;
    z-index: 1000;
  }
}
</style>
